// 引入store
import store from './store/index.js'

// 引入action
import {
  addAction,
  subAction,
  incAction,
  decAction
} from './store/actionCreators.js'

// 订阅
store.subscribe(() => {
  console.log(store.getState())
})


// 执行
// store.dispatch(addAction(10))
// store.dispatch(subAction(5))
// store.dispatch(incAction())
// store.dispatch(decAction())

// 1.函数方法
// function dispatchAndLog(action) {
//   console.log("dispatch前")
//   store.dispatch(action)
//   console.log("dispatch后")
// }
// dispatchAndLog(addAction(10))
// dispatchAndLog(subAction(5))
// dispatchAndLog(incAction())
// dispatchAndLog(decAction())

// 2.修改原有的dispatch
// hack技术:monkeyingpatch
// const next = store.dispatch
// function dispatchAndLog(action) {
//   console.log("dispatch前")
//   next(action)
//   console.log("dispatch后")
// }
// store.dispatch = dispatchAndLog
// store.dispatch(addAction(10))
// store.dispatch(subAction(5))
// store.dispatch(incAction())
// store.dispatch(decAction())

// 3.封装
function patchLogging(store) {
  const next = store.dispatch
  function dispatchAndLog(action) {
    console.log("dispatch前")
    next(action)
    console.log("dispatch后")
  }
  // store.dispatch = dispatchAndLog

  // 纯函数
  return dispatchAndLog
}

// 封装patchThunk的功能
function patchThunk(store) {
  const next = store.dispatch

  function dispatchAndThunk(action) {
    if(typeof action === "function") {
      action()
    } else {
      next(action)
    }
  }

  // store.dispatch = dispatchAndThunk

  // 纯函数
  return dispatchAndThunk
}

patchLogging(store)
patchThunk(store)
// store.dispatch(addAction(10))
// store.dispatch(subAction(5))
// store.dispatch(incAction())
// store.dispatch(decAction())

// function foo(dispatch) {
//   console.log(subAction(10))
// }

// store.dispatch(foo)

// 5.封装applyMiddleware
function applyMiddlewares(...middlewares) {
  // const newMiddlew
  middlewares.forEach(middleware => {
    store.dispatch = middleware(store)
  })
}

applyMiddlewares(patchLogging, patchThunk)

